package com.lst.api.config;

import com.lst.tools.basics.utils.RsaKeyHelper;
import com.lst.tools.redis.service.impl.RedisService;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * token  key配置
 *
 * @author: Frank
 * @date: 2019/09/24 13:51
 * @version: V1.0
 */
@Configuration
@Data
public class SecretConfig {

    public static final String ACCESS_TOKEN_PRI_KEY = "LST:ACCESS:TOKEN:PRI";
    public static final String ACCESS_TOKEN_PUB_KEY = "LST:ACCESS:TOKEN:PUB";

    @Value("${secret.access_token}")
    private String accessTokenSecret;
    @Value("${expire.access_token}")
    private int accessTokenExpire;

    @Autowired
    private RedisService redisService;

    public byte[] getAccessTokenPubKey() {
        return this.getByRedisKey(ACCESS_TOKEN_PUB_KEY);
    }

    public byte[] getAccessTokenPriKey() {
        return this.getByRedisKey(ACCESS_TOKEN_PRI_KEY);
    }


    public void createAccessTokenKey() throws IOException, NoSuchAlgorithmException {
        this.createKey(ACCESS_TOKEN_PRI_KEY, ACCESS_TOKEN_PUB_KEY, this.accessTokenSecret);
    }

    private void createKey(String redisPriKey, String redisPubKey, String secret) throws IOException, NoSuchAlgorithmException {
        String priKey = redisService.get(redisPriKey);
        String pubKey = redisService.get(redisPubKey);
        if (StringUtils.isNotBlank(priKey) && StringUtils.isNotBlank(pubKey)) {
            return;
        } else {
            /**ling-dao-pay公私钥*/
            Map<String, byte[]> keyMap = RsaKeyHelper.generateKey(secret);
            byte[] priKeyByte = keyMap.get(RsaKeyHelper.PRIVATE_KEY_BYTES);
            byte[] pubKeyByte = keyMap.get(RsaKeyHelper.PUBLIC_KEY_BYTES);
            redisService.set(redisPriKey, RsaKeyHelper.toHexString(priKeyByte));
            redisService.set(redisPubKey, RsaKeyHelper.toHexString(pubKeyByte));
        }
    }

    private byte[] getByRedisKey(String redisKey) {
        try {
            String pubKey = redisService.get(redisKey);
            if (StringUtils.isBlank(pubKey)) {
                return null;
            }
            return RsaKeyHelper.toBytes(pubKey);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
